package chances.epg.ui.taglib.json;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspException;

public class JsonFilterTag extends JsonTag {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 8018578803343534248L;
	public Object json;

	
	
	@Override
	@SuppressWarnings("rawtypes")
	public int doEndTag() throws JspException {
		List result = new ArrayList();
		Map value= (Map)this.loadFromBody();
		 if(Collection.class.isInstance(json)) {
			 Collection objs = (Collection) json;
			 for (Object object : objs) {
				Map map = (Map) object;
				if(condition(value, map)){
					result.add(map);
				}
			}	
		} 
		pageContext.setAttribute(var, result);
		this.release();
		return EVAL_PAGE;
	}
	
	
	
	@SuppressWarnings("rawtypes")
	private boolean condition(Map cond, Map map) {
		for (Object object2 : cond.entrySet()) {
			Map.Entry entry = (Map.Entry) object2;
			Object aValue = map.get(entry.getKey());
			if(!entry.getValue().equals(aValue)){
				return false;
			}
		}
		return true;
	}
	
	@Override
	public void release() {
		this.json = null;
		super.release();
	}
	public Object getJson() {
		return json;
	}
	public void setJson(Object json) {
		this.json = json;
	}
	
	
	
}
